<template>
  <common-page :common-ins="commonIns" :action-bar-data="actionBarData" :columns="COLUMNS">
    <dialog-form
      ref="dialog"
      :roles="roles"
      @filter-role="getRoleList"
      @confirm="dialogFn.confirm"
      @remove-file="dialogFn.removeFile"
    ></dialog-form>
  </common-page>
</template>

<script setup lang="ts">
import { TableRowData } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';

import $api from '@/api';
import { $confirm, dialog, useCommon, UseCommonOptions } from '@/hooks/common';
import { t } from '@/locales';
import CommonPage from '@/pages/common/page/index.vue';

import DialogForm from './components/DialogForm.vue';
import { ACTION_BAR_DATA, COLUMNS } from './constants';

const API = $api.system.manager;
const URL = import.meta.env.VITE_API_URL;
const actionBarData = ref([...ACTION_BAR_DATA]);

const commonOptions: UseCommonOptions = {
  API,
  formatItem: (data: Recordable) => {
    data.avatarUrl = data.avatar ? `${URL}${data.avatar.url}` : '';
    data.roleName = data.roles.map((v: Recordable) => v.name).join(',');
  },
};
const commonIns = useCommon(commonOptions);
const { dialogFn }: Recordable = commonIns;

commonIns.tableFn.edit = async (row: TableRowData) => {
  const res = await API.detail(row.id);
  res.roles = res.roles.map((v: Recordable) => v.id);

  dialog.value.dialogShow('edit', res);
};
commonIns.tableFn.resetpass = (row: TableRowData) => {
  const body = t('pages.manage.resetpass', { username: row.username });
  $confirm({ theme: 'danger', body }, () => {
    API.resetPass(row.id);
  });
};

dialogFn.removeFile = async (id: number) => {
  console.log(id);
  await $api.content.attachement.del(id);
  dialog.value.setData({ avatar: null });
};
dialogFn.confirm = async (type: 'add' | 'edit', data: TableRowData) => {
  const method = type === 'add' ? 'add' : 'update';

  data.roles = data.roles.map((v: Recordable) => {
    return { id: v };
  });
  if (type === 'edit' && !data.password) {
    delete data.password;
  }
  if (!data.email) {
    delete data.email;
  }
  if (!data.phoneNumber) {
    delete data.phoneNumber;
  }
  try {
    await API[method](data);
    dialog.value.dialogHide();
    commonIns.tableFn.getList();
  } catch (error) {
    dialog.value.loadingClear();
    console.log(error);
  }
};

const roles = ref([]);
const getRoleList = async (name?: string) => {
  const { items } = await $api.system.role.list({ name });
  roles.value = items.map((v: Recordable) => {
    return { label: v.name, value: v.id };
  });
};

onMounted(() => {
  getRoleList();
});
</script>
